package com.srwl.mytx.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.github.florent37.viewanimator.AnimationListener;
import com.github.florent37.viewanimator.ViewAnimator;
import com.huantansheng.easyphotos.utils.Color.ColorUtils;
import com.huantansheng.easyphotos.utils.system.SystemUtils;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.OfferRecordAdapter;
import com.srwl.mytx.domain.Advertisement;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Orders;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.AdvertisementService;
import com.srwl.mytx.utils.MoneyInputCheck;
import com.srwl.mytx.utils.PayUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.NodataFooter;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@Deprecated
public class AdvertisementActivity extends BaseActivity {
    private static final String TAG = "AdvertisementActivity";
    private static final int REFRESH_COUNT_DOWN = 1;
    @BindView(R.id.tv_live_room_title)
    TextView tv_liveRoomTitle;
    @BindView(R.id.tv_start_time)
    TextView tv_startTime;
    @BindView(R.id.tv_count_down)
    TextView tv_countDown;

    @BindView(R.id.tv_second)
    TextView tv_second;
    @BindView(R.id.tv_current_price)
    TextView tv_currentPrice;
    @BindView(R.id.refresh_layout)
    MaterialSmoothRefreshLayout refreshLayout;

    @BindView(R.id.rv_offer)
    RecyclerView rv_offer;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_offer_amount)
    EditText et_offerAmount;

    @BindView(R.id.btn_offer)
    Button btn_offer;
    @BindView(R.id.tv_second_end)
    TextView tv_secondEnd;
    private long days;
    private long hours;
    private long minutes;
    private long second;
    private List<Orders> ordersList = new ArrayList<>();
    private OfferRecordAdapter offerRecordAdapter;
    private Advertisement advertisement;
    private int page = 1;
    private int size = 10;
    private boolean hasNextPage;
    private String countDown;
    private MoneyInputCheck moneyInputCheck;
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {

            ViewAnimator.animate(tv_second).translationY(0, -tv_second.getHeight()).duration(300).onStop(new AnimationListener.Stop() {
                @Override
                public void onStop() {

                    if (isAuctionEnd) {//当倒计时解说的时候，隐藏掉显示秒相关的两个TextView
                        tv_countDown.setText("竞价已经结束");
                        tv_second.setVisibility(View.GONE);
                        tv_secondEnd.setVisibility(View.GONE);
                    } else {
                        tv_countDown.setText(countDown);
                        tv_second.setText(second + "");
                        ViewAnimator.animate(tv_second).translationY(tv_second.getHeight(), 0).duration(300).start();
                    }
                }
            }).start();
            if (!isAuctionEnd) {//倒计时没有结束，继续递归执行
                handler.postDelayed(runnable, 1000);
            } else {//倒计时结束，隐藏掉输入框和提交按键
                et_offerAmount.setVisibility(View.GONE);
                btn_offer.setVisibility(View.GONE);
            }

            //开始计算下一次显示的时间
            second--;
            if (second < 0) {//秒 小于0 ，就考虑分 是否还大于0，
                if (minutes > 0) {//如果分钟数大于0，分钟数减去 1，则把秒设置为59秒，不涉及小时和天
                    minutes--;
                    second = 59;
                    countDown = generateCountDown();
                    return;
                }
            } else {
                countDown = generateCountDown();
                return;
            }
            //分钟和秒都出现0，判断小时数量是否大于0，如果小时数量大于0，小时数量减去1，秒设置为59，分钟数设为59，不涉及天
            if (hours > 0) {
                hours--;
                second = 59;
                minutes = 59;
                countDown = generateCountDown();
                return;
            }

            //小时 分钟  秒  都出现0，判断天数是否大于0
            if (days > 0) {
                days--;
                second = 59;
                minutes = 59;
                hours = 23;
                countDown = generateCountDown();
                return;
            }
            isAuctionEnd = true;
        }
    };
    private boolean isAuctionEnd;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advertisement);
        int statusColor = ContextCompat.getColor(this, R.color.colorPrimaryDark);
        if (ColorUtils.isWhiteColor(statusColor)) {
            SystemUtils.getInstance().setStatusDark(this, true);
        }
        ButterKnife.bind(this);
        advertisement = getIntent().getParcelableExtra("advertisement");
        toolbar.setNavigationOnClickListener(v -> finish());
        tv_liveRoomTitle.setText(advertisement.getTitle());
//        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
//        tv_startTime.setText(sdf.format(advertisement.getStartDate()) + " 至 " + sdf.format(advertisement.getEndDate()));
//        tv_currentPrice.setText(Utils.numberFormat(advertisement.getAmount()));
//        long startDateTime = advertisement.getAuctionStartDate().getTime();
//        long stopDateTime = advertisement.getAuctionEndDate().getTime();
//        long currentDateTime = System.currentTimeMillis();
//        if (advertisement.getStatus() == Constant.ADVERTISEMENT_STATUS_SETTLEMENT) {
//            onAuctionStop();
//        } else if (startDateTime > currentDateTime) {
//            tv_countDown.setText(DateUtils.getTimestampString(advertisement.getAuctionStartDate()) + "竞价开始");
//            tv_secondEnd.setVisibility(View.GONE);
//            et_offerAmount.setVisibility(View.GONE);
//            btn_offer.setVisibility(View.GONE);
//        } else if (stopDateTime > currentDateTime) {
//
//            long diff = stopDateTime - currentDateTime;
//            computeAuctionEndDate(diff);
//            countDown = generateCountDown();
//            // countDown();
//            handler.post(runnable);
//
//        } else {
//            onAuctionStop();
//        }
        rv_offer.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        offerRecordAdapter = new OfferRecordAdapter(this, ordersList);
        rv_offer.setAdapter(offerRecordAdapter);
        loadData(true, false);
        initTextChangedListener();
        initRefreshLayout();
    }

    private void onAuctionStop() {
        isAuctionEnd = true;
        tv_countDown.setText("竞价已经结束");
        tv_secondEnd.setVisibility(View.GONE);
        et_offerAmount.setVisibility(View.GONE);
        btn_offer.setVisibility(View.GONE);
    }

    private void initRefreshLayout() {
        refreshLayout.setDisableRefresh(false);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                refreshData();
            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage) {
                    loadData(false, false);
                } else {
                    refreshLayout.refreshComplete();
                }
            }

        });
    }

    private void refreshData() {
        page = 1;
        loadData(false, true);
    }

    private void loadData(boolean isFirst, boolean isRefresh) {
        if (!Helper.getInstance().isNetworkConnected()){
            if (!isFirst) refreshLayout.refreshComplete();
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        Map<String, Object> info = new HashMap<>();
        info.put("page", page);
        info.put("size", size);
        info.put("advertisementId", advertisement.getId());
        if (isFirst) {
            progressBar.setVisibility(View.VISIBLE);
        }
        RetrofitManager.getInstance().createRequest(AdvertisementService.class)
                .queryOffer(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        Log.d(TAG, "onResponse: 获取出价信息完成");
                        JSONObject pageInfo = (JSONObject) result.getData();
                        hasNextPage = pageInfo.getBoolean("hasNextPage");
                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> refreshLayout.setFooterView(new NodataFooter(AdvertisementActivity.this)), 2000);
                        }
                        List<Orders> orders = pageInfo.getJSONArray("list").toJavaList(Orders.class);

                        //第一次加载数据或者是刷新数据，把第一个出价作为最高价，因为后端是按出价降序排列
                        if ((isFirst || isRefresh) && orders != null && orders.size() != 0) {
                            Double currentMaxAmount = orders.get(0).getAmount();
                            tv_currentPrice.setText(Utils.numberFormat(currentMaxAmount));
                            moneyInputCheck.setMoreThan(currentMaxAmount);//出价成功后重置输入检测的下限
                            Editable text = et_offerAmount.getText();
                            et_offerAmount.setText(text.toString());

                        }
                        if (isRefresh) {
                            ordersList.clear();
                        }
                        ordersList.addAll(orders);
                        offerRecordAdapter.notifyDataSetChanged();
                        page++;
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    private void initTextChangedListener() {

        moneyInputCheck = new MoneyInputCheck(this, new MoneyInputCheck.InteractionListener() {
            @Override
            public void showErrorMessage(String message) {
                et_offerAmount.setError(message);
                btn_offer.setEnabled(false);

            }

            @Override
            public void waitInput() {
                btn_offer.setEnabled(false);

            }

            @Override
            public void inputRight() {
                if (!isAuctionEnd) {
                    btn_offer.setEnabled(true);
                }
            }
        });
        moneyInputCheck.setMoreThan(advertisement.getAmount().doubleValue());
        et_offerAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                moneyInputCheck.onTextChanged(s);
            }

            @Override
            public void afterTextChanged(Editable s) {
                moneyInputCheck.afterTextChanged(s);
            }
        });
    }

    @OnClick(R.id.btn_offer)
    public void offer() {
        hideSoftKeyboard();
        double offerAmount = Double.valueOf(et_offerAmount.getText().toString());
        new PayUtils(offerAmount, AdvertisementActivity.this, payPassword ->
                doOffer(offerAmount, payPassword)
        );
    }

    private void doOffer(double offerAmount, String payPassword) {
        if (!Helper.getInstance().isNetworkConnected()){
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        Orders orders = new Orders();
        orders.setaId(advertisement.getId());
        orders.setAmount(offerAmount);
        Map<String, Object> body = new HashMap<>();
        if (payPassword != null) {
            body.put("payPassword", payPassword);
        }
        body.put("orders", orders);
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(AdvertisementService.class)
                .offerToAdvertisement(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.INVISIBLE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(btn_offer, getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            switch (result.getStatus()) {
                                case Constant.PAY_PASSWORD_ERROR:
                                    showToast(btn_offer, getString(R.string.pay_password_error));
                                    break;
                                case Constant.UNKNOWN_ERROR:
                                    showToast(btn_offer, getString(R.string.system_busy));
                                    break;
                                case Constant.BALANCE_NOT_ENOUGH:
                                    showToast(btn_offer, getString(R.string.balance_not_enough));
                                    break;
                                case Constant.OFFER_ERROR_AMOUNT_LOWER:
                                    showToast(btn_offer, getString(R.string.offer_amount_lower));
                                    //这种情况是，用户进入页面后，在用户出价之前，其他人已经出过更高了，所以返回出价过低，需要刷新本地页面
                                    refreshData();
                                    break;
                                case Constant.OFFER_BUSY:
                                    showToast(btn_offer, getString(R.string.system_busy));
                                    break;
                            }
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }

                        Log.d(TAG, "onResponse: 出价完成");
                        et_offerAmount.setText("");
                        //返回账户保证金总额。出价并不会对账户余额做操作，只是增加保证金的金额，任何支出都应该减去保证金后做判断是否足够
                        JSONObject jsonObject = (JSONObject) result.getData();
                        //    BigDecimal deposit = (BigDecimal) result.getData();
                        Double deposit = jsonObject.getDouble("deposit");
                        Integer offerCount = jsonObject.getInteger("offerCount");
                        UserProfileManager.getInstance().setDeposit(deposit);
                        tv_currentPrice.setText(Utils.moneyFormat(offerAmount));
                        moneyInputCheck.setMoreThan(offerAmount);//出价成功后重置输入检测的下限
                        User loginUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
                        orders.setUser(loginUserInfo);
                        orders.setOfferCount(offerCount);
                        orders.setCreated(new Date());

                        //第一次出价
                        if (ordersList.size() == 0) {
                            ordersList.add(orders);
                            offerRecordAdapter.notifyDataSetChanged();
                        } else {

                            //如果不是第一次出价，需要遍历 出价记录，看是否有历史记录，如果有，需要删除掉
                            if (offerCount != 1) {
                                boolean isEquals = false;
                                for (int i = 0; i < ordersList.size(); i++) {
                                    Orders orders1 = ordersList.get(i);
                                    if (orders1.getUser().getuId().equals(loginUserInfo.getuId())) {
                                        orders.setId(orders1.getId());//需要设置id,因为在OfferRecordActivity的onActivityResult（）中需要它
                                        setResult(RESULT_OK, new Intent().putExtra("orders", orders));
                                        isEquals = true;

                                        if (ordersList.size() == 1) {
                                            ordersList.remove(0);
                                            ordersList.add(orders);
                                            offerRecordAdapter.notifyItemChanged(0);
                                        } else {
                                            ordersList.remove(i);
                                            ordersList.add(0, orders);
                                            if (i != 0) {
                                                offerRecordAdapter.notifyItemMoved(i, 0);
                                            }
                                            offerRecordAdapter.notifyItemChanged(0);
                                        }
                                        break;
                                    }
                                }
                                //没有历史出价的情况
                                if (!isEquals) {
                                    ordersList.add(0, orders);
                                    offerRecordAdapter.notifyItemInserted(0);
                                }
                            } else {
                                ordersList.add(0, orders);
                                offerRecordAdapter.notifyItemInserted(0);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        progressBar.setVisibility(View.INVISIBLE);
                    }
                });
    }


    private void computeAuctionEndDate(long diff) {
        days = diff / (1000 * 60 * 60 * 24);
        hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
        second = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60) - minutes * (1000 * 60)) / 1000;
    }

    private String generateCountDown() {

        // return "还有" + days + "天" + hours + "小时" + minutes + "分" + second + "秒竞价结束";
        if (days != 0) {
            return "还有" + days + "天" + hours + "小时" + minutes + "分";
        } else if (hours != 0) {
            return "还有" + hours + "小时" + minutes + "分";
        } else {
            return "还有" + minutes + "分";
        }
    }

    /**
     * 用Timer加handler 或者Timer加runOnUiThread 都会出现跳秒
     */
    @Deprecated
    private void countDown() {
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {

                handler.sendEmptyMessage(1);
                if (countDown.equals("竞价结束")) {
                    timer.cancel();
                }
                second--;
                if (second == -1) {//前一次的秒 是0 ，就考虑分钟数是否还有大于0，
                    if (minutes > 0) {//如果分钟数大于0，分钟数减去 1，则把秒设置为59秒，不涉及小时和天
                        minutes--;
                        second = 59;
                        countDown = generateCountDown();
                        return;
                    }
                } else {//前一次 秒数量不是0，
                    countDown = generateCountDown();
                    return;
                }
                //分钟和秒都出现0，判断小时数量是否大于0，如果小时数量大于0，小时数量减去1，秒设置为59，分钟数设为59，不涉及天
                if (hours > 0) {
                    hours--;
                    second = 59;
                    minutes = 59;
                    countDown = generateCountDown();
                    return;
                }

                //小时 分钟  秒  都出现0，判断天数是否大于0
                if (days > 0) {
                    days--;
                    second = 59;
                    minutes = 59;
                    hours = 23;
                    countDown = generateCountDown();
                    return;
                }
                countDown = "竞价结束";

            }
        };

        timer.schedule(timerTask, 0, 1000);


    }

    void showCountDown() {
        countDown = generateCountDown();

    }
}
